//1 导入http模块
let http = require('http');
let https  = require('https');

let url = require('url');
const cheerio  = require('cheerio');  //导入第三方模块
//2 创建服务对象
const server = http.createServer()

server.on('request',(req,res)=>{
    //跨域（跟浏览器相关，前端后端的端口号不同）
    const urlObj=url.parse(req.url,true)

    res.writeHead(200,{
        //跨域（xxx策略）
        'Access-Control-Allow-Origin':'*' ,  //允许所有域都可以跨
        "content-type":"application/json;charset=utf-8" , //设置响应头格式和编码
    })

    if(urlObj.pathname==='/api/getInfo'){
        httpget((data)=>{
            return res.end(spider(data))
        })
    }else{
        res.end('404')
    }
})

// 获取数据https://i.maoyan.com/#movie
function httpget(cp){
    let data = ''
    https.get('https://i.maoyan.com/',(res)=>{
        res.on('data',(chunk)=>{   //监听response的状态，如果状态一直是data，说明还在接收数据，chunk数据片段
           data += chunk
        })

        res.on('end',()=>{  //监听response的状态，如果状态是end，说明接收完毕
            cp(data)
        })
    })
}

function spider(data){
    const $ = cheerio.load(data)
    let $movieList=$('.column.content')
    let movies=[]
    $movieList.each((index,value)=>{
        movies.push({
            title:$(value).find('.title').text(),
            grade:$(value).find('.grade').text(),
            actor:$(value).find('.actor').attr('title'),
        })
    })
    console.log(movies)
    return JSON.stringify(movies)
}

server.listen(80,()=>{
    console.log('http://127.0.0.1')
})